# encoding: utf-8
# @author: wangxin
# @software: garner
# @file: writeViews.py
# @time: 2025/2/20 19:44

from venv import logger

from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from unicodedata import category

from home.models import Articlecategory, Article


class writeView(View):
    def get(self, request):
        categories = Articlecategory.objects.all()

        context={
            'categories': categories
        }
        return render(request, 'write_blog.html',context=context)

    def post(self, request):
        avatar=request.FILES.get('avatar')
        title=request.POST.get('title')
        category_id=request.POST.get('category')
        sumary=request.POST.get('sumary')
        content=request.POST.get('content')
        tags=request.POST.get('tags')
        user=request.user.id

        if not avatar:
            avatar='/img/404.png'
        if not category_id:
            category_id=1
        if not sumary:
            sumary=content[:25]

        if not all([avatar,title,category_id,sumary,content]):
            return render(request, 'write_blog.html',{'errmsg':'请填写完整'})
        try:
            category=Articlecategory.objects.get(id=category_id)
        except Articlecategory.DoesNotExist:
            return render(request, 'write_blog.html',{'errmsg':'请选择正确的分类'})
        try:
            article=Article.objects.create(
                avatar=avatar,
                title=title,
                category=category,
                sumary=sumary,
                content=content,
                tags=tags,
                author_id=user


            )
        except Exception as e:
            print(e)
            return render(request, 'write_blog.html',{'errmsg':'发布失败'})
        return redirect(reverse('index'))